package com.springBoot.service.impl;


import com.springBoot.commonClass.Utils;
import com.springBoot.entity.ObjectsEntity;
import com.springBoot.exception.BusinessFailureException;
import com.springBoot.repository.ObjectsRepository;
import com.springBoot.service.ObjectsService;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ObjectsServiceImpl implements ObjectsService {

    @Autowired
    private ObjectsRepository objectsRepository;

    @Override
    public List<ObjectsEntity> retrieveByParams(ObjectsEntity objEntity) {

        List<ObjectsEntity> result;
        try{
            ReflectionToStringBuilder.toString(objEntity);
            result = objectsRepository.selectByParams(objEntity);
        }catch (Exception e){
            System.out.println("---------------error" + e.getMessage());
            throw e;
//            throw new BusinessFailureException(false);
        }
        return result;
    }

    @Override
    public ObjectsEntity InsertNewObj(ObjectsEntity objEntity) {
        objEntity.setObjId(Utils.getUuid());
//        objEntity.setOrgId(Utils.getUuid());
//        objEntity.setOwnerId(Utils.getUuid());
        try{
            Integer result = objectsRepository.insert(objEntity);
            if(result != 1){
                throw new BusinessFailureException(false);
            }
        }catch (Exception e){
            System.out.println("-------------error" + e.getMessage());
            throw e;
        }
        return objectsRepository.selectByParams(objEntity).get(0);
    }

    @Override
    public ObjectsEntity updateObj(ObjectsEntity objEntity) {
        try{
            ObjectsEntity result;
            result = objectsRepository.selectForUpdate(objEntity);
            if(result != null){
                objectsRepository.update(objEntity);
            }
        }catch (Exception e){
            System.out.println("-------------error" + e.getMessage());
            throw e;
        }
        return objectsRepository.selectByParams(objEntity).get(0);
    }

    @Override
    public void deleteObj(ObjectsEntity objEntity) {
        try{
            objectsRepository.delete(objEntity);
        }catch (Exception e){
            System.out.println("---------------error" + e.getMessage());
            throw e;
        }
    }
}
